import os
import django
import sys
import shutil
import traceback

pro_dir = os.getcwd()
sys.path.append(pro_dir)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mitagger.settings")

from home.models import Image
from home.files import createFolder, convertFormat

def get_images_dict(basepath, image_name_list):
    res_dict = dict()
    for parentDir, dirnames, filenames in os.walk(basepath):
        for filename in filenames:
            if filename in image_name_list:
                full_path = (parentDir if parentDir.endswith('/') else parentDir + '/') + filename
                res_dict[filename] = full_path
    print len(res_dict)
    return res_dict

def save_path_info(basepath, img, path, filename):
    print basepath
    shutil.copyfile(path, basepath+filename)
    img.image_file_location = convertFormat(basepath+filename)
    img.save()


def set_null_filepath(path_dict, img_list):
    basepath = createFolder('image')
    null_imgs = Image.objects.filter(file_name__in=img_list, image_file_location=None)
    for img in null_imgs:
        try:
            save_path_info(basepath, img, path_dict[img.file_name], img.file_name)
        except:
            traceback.print_exc()
            continue
    print len(path_dict)

if __name__ == '__main__':
    django.setup()
    no_tag_file = open('no_tags.txt')
    img_lists = []
    for line in no_tag_file:
        if line.endswith('\n'):
            line = line[:-1]
        img_lists.append(line)
    set_null_filepath(get_images_dict('./images', img_lists), img_lists)
